const Sequelize = require('sequelize')
const bcrypt = require('bcryptjs')
const sequelize = require('../db')

class User extends Sequelize.Model {
  //  邮箱密码登录方式验证
  static async validateEmailLogin(email, plainPassword) {
    const user = await User.findOne({
      where: {
        email
      }
    })
    if (!user) {
      throw new global.errs.NotFound()
    }
    const correct = bcrypt.compareSync(plainPassword, user.password)
    if (!correct) {
      throw new global.errs.AuthFailed('密码错误')
    }
    return user
  }

  //  查询openid是否存在，若存在则直接返回user
  static async getUserByOpenid(openid) {
    const user = await User.findOne({
      where: {
        openid
      }
    })
    return user
  }

  // 根据openid创建用户(openid不存在的情况下)
  static async addUserByOpenid(openid) {
    return await User.create({
      openid
    })
  }
}


User.init({
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  nickname: Sequelize.STRING,
  email: {
    type: Sequelize.STRING,
    unique: true
  },
  password: {
    type: Sequelize.STRING,
    set(val) {
      const salt = bcrypt.genSaltSync(10)
      const pwd = bcrypt.hashSync(val, salt)
      this.setDataValue('password', pwd)
    }
  },
  openid: {
    type: Sequelize.STRING(64),
    unique: true
  }
}, {sequelize, tableName: 'user'})


module.exports = User